// ref:
// - https://umijs.org/plugins/api
import { IApi } from '@umijs/types';
import defaultConfig from './defaultConfig';
import { RouteModal, DefaultConfigModal, AuthResultModal } from './modal';
import { routesProvider } from './buildUtils/route';
import paths from './paths';
import { join } from 'path';
import writeTmpFile from './writeTmpFile';
import { setInit } from './buildUtils/check';
import { request } from './buildUtils/request';

export default function(api: IApi) {
  let authData: AuthResultModal = {
    components: [],
    apis: [],
    routes: [],
  };

  api.describe({
    key: 'hwAuth',
    config: {
      default: defaultConfig,
      schema: joi => {
        return joi.object().keys({
          locals: joi.object(),
          nameProvider: joi.any(),
          authProxyAuto: joi.boolean(),
          request: joi.any(),
          appKey: joi.string(),
        });
      },
    },
  });

  api.modifyRoutes(routes => {
    setInit();
    const fnRoutes = routes as RouteModal[];
    const config = api.config.hwAuth as DefaultConfigModal;
    const { appKey } = config;
    const result = routesProvider(config, fnRoutes, {
      auth: appKey,
    } as RouteModal);
    result.appKey = appKey;

    authData = result;

    return result.routes;
  }); //修改路由，把自定义参数加入路由

  api.onGenerateFiles(() => {
    writeTmpFile(api, authData);
  });

  api.onBuildComplete(async () => {
    const subAuth = request(api, authData);

    if (!subAuth) {
      return;
    }

    try {
      await subAuth();
      api.logger.info('上传权限成功!');
    } catch (e) {
      api.logger.error(e.message);
    }
  });

  api.addUmiExports(() => {
    return [
      {
        source: join('../', paths.exportModal),
        exportAll: true,
      },
      {
        source: join('../', paths.exportAuthContext),
        exportAll: true,
      },
      {
        source: join('../', paths.exportCheckAuthComponent),
        exportAll: true,
      },
      {
        source: join('../', paths.exportSettingAuthContext),
        exportAll: true,
      },
      {
        source: join('../', paths.exportAuthCheckHooks),
        exportAll: true,
      },
      {
        source: join('../', paths.exportAuthCheck),
        exportAll: true,
      },
    ];
  });
}
